<template>
  <div
    ref="chartDiv"
    :style="'width: 100%;height: ' + (height ? height : '200px')"
  ></div>
</template>

<script setup>
import { ref, onMounted, nextTick, markRaw, watch } from 'vue';
import * as echarts from "echarts";
import prettyBytes from 'pretty-bytes';

const props = defineProps({
  label: String,
  datasets: Array,
  data: Array,
  formatter: Boolean,
  height: String
});
const chartDiv = ref();
const currChart = ref(null);
const zLevel = ref(100);

const init = async() => {
  const color = props.datasets.length >= 3
    ? ['#68DCB7', '#65A5D9', '#FFE6A1']
    : ['#65A5D9', '#FFE6A1']
  const labels = props.data.map(d => d[props.label]);
  const series = props.datasets.map(id => {
    return {
      name: id,
      type: 'line',
      areaStyle: {
        origin: 'start',
        opacity: 1
      },
      emphasis: { disabled: true },
      showSymbol: false,
      zlevel: zLevel.value--,
      data: props.data.map(d => d[id])
    };
  });

  const option = {
    color: color,
    grid: {
      top: '20px',
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: labels
      }
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          formatter: (value) => {
            return props.formatter ? prettyBytes(value) : value;
          }
        }
      }
    ],
    series: series
  };

  if (!currChart.value) {
    currChart.value = markRaw(echarts.init(chartDiv.value));
  }
  currChart.value.setOption(option);
  await nextTick(() => {
    try {
      currChart.value.resize();
    } catch (e) {
      console.log(e);
    }
  });
};

watch(() => props.data, () => {
  init();
}, {deep: true});

onMounted(() => {
  init();
});
</script>